<template>
  <PageWrapper title="">
    <vxe-grid ref='xGrid' v-bind="gridOptions"
    @checkbox-change="checkboxChange"
    @checkbox-all="checkboxAll"
    @checkbox-range-change="checkboxRangeChange">
      <template #form>
        <vxe-form :data="formConditionData.data" title-colon collapse-status>
          <vxe-form-item title="用户" field="userId" :folding="false">
            <template #default="{ data }">
              <vxe-select v-model="data.userId"
                          placeholder="请选择"
                          :options="selectUserList"
                          clearable
                          @change="handleSuccess">
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item title="模块" field="groupName" :folding="false">
            <template #default="{ data }">
              <vxe-select v-model="data.groupName"
                          placeholder="请选择"
                          :options="selectGroupNameList"
                          clearable
                          @change="handleSuccess">
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item title="子模块" field="name" :folding="false">
            <template #default="{ data }">
              <vxe-select v-model="data.name"
                          placeholder="请选择"
                          :options="selectNameList"
                          clearable
                          @change="handleSuccess">
              </vxe-select>
            </template>
          </vxe-form-item>
          <!-- <vxe-form-item collapseNode>
            <template #default>
              <vxe-button status="warning" icon="vxe-icon--more" @click="">查询</vxe-button>
            </template>
          </vxe-form-item> -->
        </vxe-form>
      </template>
      <template #toolbar_buttons>
        <popconfirm
          placement="top"
          title="慎重！批量删除【选中的数据】吗?"
          ok-text="删除"
          cancel-text="取消"
          :disabled="deleteAllShow"
          @confirm="deleteAll">
          <vxe-button icon="vxe-icon--close" status="danger" :disabled="deleteAllShow">批量删除</vxe-button>
        </popconfirm>
      </template>
      <template #operate="{ row }">
        <popconfirm
          placement="topRight"
          title="慎重！确定删除【单行数据】吗?"
          ok-text="删除"
          cancel-text="取消"
          @confirm="deleteOne([row.id] as any)">
          <vxe-button status="danger" icon="vxe-icon--close" title="删除" circle></vxe-button>
        </popconfirm>
      </template>
    </vxe-grid>
  </PageWrapper>
</template>
<script lang="ts" name="Log" setup>
import { Popconfirm } from 'ant-design-vue';
import _ from 'lodash-es';
import { reactive, ref } from 'vue';
import { SizeType, VxeGridProps } from 'vxe-table';
import { columns } from './data';
import { deletes, getTableData } from '/@/api/admin/log';
import { PageWrapper } from '/@/components/Page';

const selectUserList = ref([]);
const selectGroupNameList = ref([]);
const selectNameList = ref([]);
const formConditionData = reactive({data: {}})
const xGrid = ref()
const size = ref<SizeType>('mini')
const gridOptions = reactive<VxeGridProps>({
  border: true,
  resizable: true,
  showHeaderOverflow: true,
  showOverflow: false,
  highlightHoverRow: true,
  keepSource: true,
  id: 'xGrid1',
  height: window.innerHeight-113,
  size: size.value,
  rowId: 'id',
  columns: columns,
  // data: [],
  columnConfig: {
    isCurrent: true,
    isHover: true,
  },
  rowConfig: {
    isCurrent: true,
    isHover: false,
  },
  customConfig: {
    storage: true,
  },
  printConfig: {
    columns: [
      {field: 'name'},
    ]
  },
  sortConfig: {
    trigger: 'cell',
    remote: false
  },
  filterConfig: {
    remote: false
  },
  pagerConfig: {
    total: 0,
    currentPage: 1,
    pageSize: 20,
    pageSizes: [20, 50, 100, 200, 500, 1000],
    layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'],
    border: true,
    background: true,
    perfect: true,
  },
  toolbarConfig: {
    refresh: true,
    import: false,
    export: true,
    print: false,
    zoom: true,
    custom: true,
    slots: {
      buttons: 'toolbar_buttons',
    },
  },
  exportConfig: {
    remote: false,
    types: ['csv'],
    modes: ['current', 'selected', 'all'],
  },
  checkboxConfig: {
    // labelField: 'id',
    reserve: true,
    highlight: true,
    range: true,
    trigger: 'cell',
  },
  proxyConfig: {
    ajax: {
      async query({ page, sort, sorts, filters, form }) {
        let params = Object.assign({}, page, formConditionData.data)
        let rows = {page:{}, result: []}
        await getTableData(params).then(d => {
          let {page, result, other} = d
          rows.page = page
          rows.result = result
          if (other) {
            let {userList, policyList} = other
            selectUserList.value = userList && userList.map((e:any) => {
              return {label: e.name, value: e.id}
            })
            //
            let arr1 = policyList && policyList.map((e:any) => {
              return {label: e.groupName, value: e.groupName}
            })
            selectGroupNameList.value = _.uniqBy(arr1, "value") as never
            //
            let arr2 = policyList && policyList.map((e:any) => {
              return {label: e.name, value: e.name}
            })
            selectNameList.value = _.uniqBy(arr2, "value") as never
          }
        })
        deleteAllShow.value = true
        return Promise.resolve(rows)
      },
      queryAll({ page, sort, sorts, filters, form }) {
        return Promise.resolve([])
      }
    }
  },
});

const deleteOne = (params: []) => {
  deletes(params).then(() => {
    deleteAllShow.value = true
    handleSuccess()
  })
}
const deleteAll = () => {
  let checkedList = xGrid.value.getCheckboxRecords(true).map(e => e.id)
  deleteOne(checkedList)
}

const deleteAllShow = ref(true)
const checkboxChange = ({ checked, row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }) => {
  deleteAllShow.value = !(xGrid.value.getCheckboxRecords(true).length > 0)
}
const checkboxAll = ({ checked, $event }) => {
  deleteAllShow.value = !checked
}
const checkboxRangeChange = ({ $event }) => {
  deleteAllShow.value = !(xGrid.value.getCheckboxRecords(true).length > 0)
}

const handleSuccess = () => {
  gridOptions.loading = true;
  let {pager} = xGrid.value.getProxyInfo()
  let params = Object.assign({}, pager, formConditionData.data)
  getTableData(params).then(dd => {
    xGrid.value.loadData(dd?.result)
    let {pager} = xGrid.value.getProxyInfo()
    pager.total = dd?.page?.total
    gridOptions.loading = false
  }).catch(() => gridOptions.loading = false)
  deleteAllShow.value = true
}
</script>
